import React, { useCallback } from 'react';
import { FormattedMessage } from 'react-intl';
import { Head } from 'ice';
import { Button, Card, Dialog, Field, Icon, Input, Pagination, ResponsiveGrid, Table, Tag } from '@alifd/next';
import { useFusionTable, useSetState } from 'ahooks';
import PageHeader from '@/components/PageHeader';
import userService from '@/services/user';
import store from '@/store';
import styles from './index.module.scss';
import DialogOperation from './components/DialogOperation';

const TableActionIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1899388_oxn3zhg34oj.js',
});

const User = () => {
  const [state, setState] = useSetState({
    optCol: null,
    actionType: 'preview',
    actionVisible: false,
    loading: false,
    isZebra: false,
    size: 'medium',
    multipleDelBtnDis: true,
    selected: [],
  });
  const { actionVisible, optCol } = state;
  const userDispatchers = store.useModelDispatchers('user');
  const field = Field.useField([]);

  const { tableProps, paginationProps, search } = useFusionTable(userService.getUsers, {
    defaultPageSize: 15,
    field,
    cacheKey: 'tableProps',
    formatResult: (response) => {
      return {
        list: response.page.list,
        total: response.page.totalCount,
      };
    },
  });

  const { reset } = search;

  const operationCallback = useCallback(
    ({ actionType, dataSource }) => {
      setState({
        actionType,
        optCol: dataSource,
        actionVisible: true,
      });
    },
    [setState],
  );

  const handleCancel = useCallback(() => {
    setState({ actionVisible: false });
  }, [setState]);

  const handleOk = useCallback(
    (values) => {
      const { actionType } = state;
      if (actionType === 'preview') {
        handleCancel();
      } else if (actionType === 'add') {
        setState({ loading: true });
        userDispatchers.createUser(values).then(() => {
          reset();
          handleCancel();
          setState({ loading: false });
        });
      } else if (actionType === 'edit') {
        setState({ loading: true });
        userDispatchers.updateUser(values).then(() => {
          reset();
          handleCancel();
          setState({ loading: false });
        });
      }
    },
    [state, handleCancel, setState, userDispatchers, reset],
  );

  const handleDelete = useCallback(
    (data) => {
      if (!data) {
        return;
      }
      Dialog.confirm({
        title: '删除提醒',
        content: `确定删除 ${data.username} 吗？`,
        onOk: () => {
          userDispatchers.delUsers([data.userId]).then(() => {
            reset();
          });
        },
      });
    },
    [reset, userDispatchers],
  );

  const handleDeletes = useCallback(() => {
    if (state.selected.length > 0) {
      setState({ multipleDelBtnDis: true });
      Dialog.confirm({
        title: '删除提醒',
        content: '确定要批量删除吗？',
        onOk: () => {
          userDispatchers.delUsers(state.selected).then(() => {
            reset();
          });
        },
      });
    }
  }, [reset, setState, state.selected, userDispatchers]);

  const cellOperation = (...args) => {
    const record = args[2];
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <Button text type="primary" onClick={() => operationCallback({ actionType: 'edit', dataSource: record })}>
          <FormattedMessage id="app.user.edit" />
        </Button>
        <Button text type="primary" onClick={() => handleDelete(record)} disabled={record.userId === 1}>
          删除
        </Button>
        <Button text type="primary" onClick={() => operationCallback({ actionType: 'preview', dataSource: record })}>
          查看
        </Button>
      </div>
    );
  };

  const stateCell = (value) => {
    let cell;
    switch (value) {
      case 1:
        cell = (
          <Tag type="normal" color="green" size="small">
            正常
          </Tag>
        );
        break;
      default:
        cell = (
          <Tag type="normal" color="red" size="small">
            禁用
          </Tag>
        );
        break;
    }
    return cell;
  };

  return (
    <ResponsiveGrid gap={20}>
      <Head>
        <title>用户管理</title>
      </Head>
      <ResponsiveGrid.Cell colSpan={12}>
        <PageHeader breadcrumbs={[{ name: '系统管理' }, { name: '用户管理' }]} />
      </ResponsiveGrid.Cell>
      <ResponsiveGrid.Cell colSpan={12}>
        <Card free className={styles.container} id="table-container">
          <Card.Content>
            <div className={styles.actionBar}>
              <div className={styles.search}>
                <Input placeholder="用户名" />
                <div className={styles.buttonGroup}>
                  <Button type="normal">查询</Button>
                  <Button type="primary" onClick={() => operationCallback({ actionType: 'add', dataSource: {} })}>
                    新增
                  </Button>
                  <Button type="primary" warning disabled={state.multipleDelBtnDis} onClick={handleDeletes}>
                    批量删除
                  </Button>
                </div>
              </div>
              <div className={styles.rightButtonGroup}>
                <Button text onClick={() => setState({ size: state.size === 'medium' ? 'small' : 'medium' })}>
                  <TableActionIcon type="narrow" size="small" />
                </Button>
                <Button text onClick={() => setState({ isZebra: !state.isZebra })}>
                  <TableActionIcon type="zebra" size="small" />
                </Button>
              </div>
            </div>
            <Table
              {...tableProps}
              primaryKey="userId"
              rowSelection={{
                getProps: (record) => {
                  if (record.userId === 1) {
                    return { disabled: true };
                  }
                },
                onChange: (selectedRowKeys) => {
                  if (selectedRowKeys.length > 0) {
                    setState({ multipleDelBtnDis: false, selected: selectedRowKeys });
                  } else {
                    setState({ multipleDelBtnDis: true, selected: [] });
                  }
                },
              }}
              size={state.size}
              isZebra={state.isZebra}
            >
              <Table.Column title="ID" dataIndex="userId" width={80} sortable />
              <Table.Column title="用户名" dataIndex="username" sortable />
              <Table.Column title="邮箱" dataIndex="email" sortable />
              <Table.Column title="手机号" dataIndex="mobile" width={120} sortable />
              <Table.Column title="状态" dataIndex="status" width={100} align="center" cell={stateCell} sortable />
              <Table.Column title="创建时间" dataIndex="createTime" width={180} align="center" sortable />
              <Table.Column title="操作" dataIndex="userId" width={150} align="center" cell={cellOperation} />
            </Table>
            <Pagination style={{ marginTop: '1rem' }} {...paginationProps} />
          </Card.Content>
        </Card>
        <DialogOperation
          visible={actionVisible}
          actionType={state.actionType}
          dataSource={optCol}
          onOk={handleOk}
          onClose={handleCancel}
          onCancel={handleCancel}
          loading={state.loading}
        />
      </ResponsiveGrid.Cell>
    </ResponsiveGrid>
  );
};

export default User;
